﻿using System;
using System.Collections.Generic;

namespace QQ2564874169.Core.ORM
{
    public class DataSort
    {
        public List<string> Sorts { get; } = new List<string>();

        public DataSort()
        {

        }

        public DataSort(string expr)
        {
            foreach (var row in expr.Split(','))
            {
                if (string.IsNullOrEmpty(row)) continue;
                Sorts.Add(row);
            }
        }

        public void Check()
        {
            foreach (var item in Sorts)
            {
                if (item.Contains(" ") || item.Contains("\\"))
                    throw new ArgumentException("排序格式是name或者!name，!表示倒序。");
            }
        }

        private string ToOrderSql()
        {
            var sql = "ORDER BY";

            foreach (var item in Sorts)
            {
                if (item.Contains(" "))
                    throw new ArgumentException("排序格式是name或者!name，!表示倒序。");
                if (item.StartsWith("!"))
                {
                    sql += " " + item.Substring(1) + " DESC";
                }
                else
                {
                    sql += " " + item + " ASC";
                }
            }
            return sql;
        }
    }

    public class PageSet : DataSort
    {
        public int Count { get; set; }
        public int Index { get; set; }

        public PageSet(int index = 1, int count = 10)
        {
            Count = count;
            Index = index;
        }

        //private string ToCountSql(string sourceSql)
        //{
        //    return $"SELECT COUNT(1) FROM({sourceSql}) T";
        //}

        //private string ToDataSql(string sourceSql)
        //{
        //    var start = (Index - 1) * Count;
        //    var end = start + Count + 1;
        //    var ordersql = Sorts.Count > 0 ? ToOrderSql() : "ORDER BY (SELECT 0)";

        //    return $@"SELECT * FROM (
        //                SELECT *,ROW_NUMBER() OVER({ordersql}) PAGEROW FROM ({sourceSql}) T
        //              ) T WHERE PAGEROW>{start} AND PAGEROW<{end}";
        //}
    }
}
